﻿package fj.ui
{
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	
	import fj.events.FJScrollbarEvent;
	
	public class FJScrollbar extends MovieClip
	{
		public var _handler:MovieClip;
		public var _rail:MovieClip;
		
		private var yOffset:Number;
		private var yMin:Number;
		private var yMax:Number;

		public function FJScrollbar():void
		{
			_handler = getChildByName( "handler" ) as MovieClip;
			_rail = getChildByName( "rail" ) as MovieClip;
			
			yMin = 0;
			yMax = _rail.height - _handler.height;
			_handler.buttonMode = true;
			_handler.addEventListener( MouseEvent.MOUSE_DOWN, _handlerDown );
		}
		public function scroll( s:Number ):void
		{
			_handler.y += s;
			if ( _handler.y <= yMin ) {
				_handler.y = yMin;
			}
			if ( _handler.y >= yMax ) {
				_handler.y = yMax;
			}
			dispatchEvent( new FJScrollbarEvent( _handler.y / yMax ) );
		}
		private function _handlerDown( e:MouseEvent ):void
		{
			yOffset = mouseY - _handler.y;
			stage.addEventListener( MouseEvent.MOUSE_MOVE, _handlerMove );
			stage.addEventListener( MouseEvent.MOUSE_UP, _handlerUp );
		}
		private function _handlerUp( e:MouseEvent ):void
		{
			stage.removeEventListener( MouseEvent.MOUSE_MOVE, _handlerMove );
			stage.removeEventListener( MouseEvent.MOUSE_UP, _handlerUp );
		}
		private function _handlerMove( e:MouseEvent ):void
		{
			_handler.y = mouseY - yOffset;
			if ( _handler.y <= yMin ) {
				_handler.y = yMin;
			}
			if ( _handler.y >= yMax ) {
				_handler.y = yMax;
			}
			dispatchEvent( new FJScrollbarEvent( _handler.y / yMax ) );
		}
	}
}